package com.boyinet.activation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boyinet.activation.entity.Order;
import com.boyinet.activation.mapper.OrderMapper;
import com.boyinet.activation.service.OrderService;
import com.boyinet.activation.util.CDKeyUtil;
import com.boyinet.activation.util.R;
import com.boyinet.activation.vo.OrderVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * @author lengchunyun
 */
@RequestMapping("order")
@RestController
@Slf4j
public class OrderController {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderService orderService;


    /**
     * SN 订单生成
     *
     * @param order 订单信息
     * @return SN值
     */
    @PostMapping("create")
    @ResponseBody
    public R create(@RequestBody Order order) {
        log.info("[生成订单]==>{}", order);
        R r = R.error();
        if (checkOrderInfo(order, r)) {
            final String cdk;
            try {
                cdk = CDKeyUtil.createCDkey(order.getMac(), order.getSoftwareCode(), order.getDeadline());
                order.setCdk(cdk);
                order.setCreateTime(LocalDateTime.now());
                orderService.save(order);
                return R.ok("订单生成完毕").put("data",cdk);
            } catch (Exception e) {
                e.printStackTrace();
                return R.error(e.getMessage());
            }
        } else {
            return r;
        }
    }


    @GetMapping("getById")
    public R getById(Long id) {
        System.out.println(id);
        Order order = orderService.getById(id);
        log.info("[订单信息为]=={}", order);
        return R.ok().put("data", order);
    }

    /**
     * '
     * SN订单回退为未启用状态
     *
     * @param obj SN
     */
    @PostMapping("rollback")
    public void rollback(@RequestBody RequestObj obj) {
        orderMapper.rollback(obj.sn);
    }


    public static String genRandomNum(int length) {
        // 62是因为数组是从0开始的，26个小写字母+10个数字+26个大写字母
        final int maxNum = 62;
        // 生成的随机数
        int i;
        // 生成的密码的长度
        int count = 0;
        char[] str = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9'};

        StringBuilder pwd = new StringBuilder();
        Random r = new Random();
        while (count < length) {
            // 生成随机数，取绝对值，防止生成负数，生成的数最大为62-1
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }


    @Data
    static class RequestObj {
        String sn;
        String pass;
    }

    /**
     * 分页列表显示所有订单
     *
     * @return 响应数据
     */
    @PostMapping("list")
    public R listOrder(@RequestBody OrderVO condition) {
        Page<Order> list = orderService.listByPage( condition);
        Map<String, Object> map = new HashMap<>(4);
        map.put("count", list.getTotal());
        map.put("pi", condition.getPage());
        map.put("ps", condition.getLimit());
        map.put("data", list.getRecords());
        return R.ok(map);
    }


    private boolean checkOrderInfo(Order order, R r) {
        if (StringUtils.isBlank(order.getName())) {
            r.put("msg","联系人为空！");
            return false;
        }
        if (StringUtils.isBlank(order.getPhone()) && StringUtils.isBlank(order.getEmail())) {
            r.put("msg","联系方式至少选填一种！");
            return false;
        }
        Pattern emailPattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");

        if (StringUtils.isNotBlank(order.getEmail()) && !emailPattern.matcher(order.getEmail()).matches()) {
            r.put("msg","邮箱格式不合法！");
            return false;
        }

        Pattern phonePattern = Pattern.compile("^1[3456789]\\d{9}$");
        if (StringUtils.isNotBlank(order.getPhone()) && !phonePattern.matcher(order.getPhone()).matches()) {
            r.put("msg","手机号不合法！");
            return false;
        }
        if (StringUtils.isBlank(order.getCompanyName())) {
            r.put("msg","公司名称为空！");
            return false;
        }
        if (StringUtils.isBlank(order.getSoftwareCode())) {
            r.put("msg","软件编码为空！");
            return false;
        }

        Pattern macPattern = Pattern.compile("^[0-9A-F]{8}$");
        if (StringUtils.isBlank(order.getSoftwareCode())) {
            r.put("msg","机器码为空！");
            return false;
        }

        if (StringUtils.isNotBlank(order.getSoftwareCode()) && !macPattern.matcher(order.getMac()).matches()) {
            r.put("msg","机器码不合法！");
            return false;
        }
        return true;
    }

}
